
import AbsWindow from "../../framework/AbsWindow";
import { WindowName } from "../../framework/reflect/WindowName";
import { timer } from ".././utils/TimeSpan";
import SettlementWindow from "./SettlementWindow";
import Context from "../../framework/Context";
import LoadResData from "../../framework/LoadResData";
import LoseWindow from "./LoseWindow";
import LocalStorage from "../../framework/utils/LocalStorage";
import ForgeWindow from "./ForgeWindow";
import { WxEvent } from "../../framework/wx/WxEvent";
import TalentPopup from "../popups/TalentPopup";

const { ccclass, property } = cc._decorator;

@ccclass
@WindowName("GameWindow")
export default class GameWindow extends AbsWindow {

    @property(cc.ProgressBar)
    private countProgressBar: cc.ProgressBar = null;
    @property(cc.ProgressBar)
    private timerProgressBar: cc.ProgressBar = null;
    @property(cc.Label)
    private timerLabel: cc.Label = null;
    @property(cc.Label)
    private label: cc.Label = null;
    @property(cc.Button)
    private Btn1: cc.Button = null;
    @property(cc.Button)
    private Btn2: cc.Button = null;
    @property(cc.Button)
    private Btn3: cc.Button = null;
    @property(cc.Button)
    private Btn4: cc.Button = null;
    @property(cc.Button)
    private Btn5: cc.Node = null;
    @property(cc.Button)
    private Btn6: cc.Button = null;
    @property(cc.Button)
    private Btn7: cc.Button = null;
    @property(cc.Button)
    private Btn8: cc.Button = null;
    @property(cc.Button)
    private Btn9: cc.Button = null;
    @property(cc.Prefab)
    private Lprefab: cc.Prefab = null;
    @property(cc.Prefab)
    private Superprefab: cc.Prefab = null;
    @property(cc.Node)
    private actionNode: cc.Node = null;
    @property(cc.Node)
    private superNode: cc.Node = null;
    @property(cc.Node)
    private speed: cc.Node = null;
    @property(cc.Label)
    private combatantNumberLabel: cc.Label = null;
    @property(cc.Prefab)
    private goldAnimPrefab: cc.Prefab = null;
    @property(cc.Prefab)
    private fluencyAnim: cc.Prefab = null;
    @property(cc.Prefab)
    private subAnim: cc.Prefab = null;
    @property(cc.Node)
    private showWeaponUI: cc.Node = null;
    @property(cc.Node)
    private toggleNode: cc.Node = null;
    @property(cc.Prefab)
    private forgeState: (cc.Prefab) = null;
    @property(cc.Prefab)
    private combatant: (cc.Prefab) = null;

    private count: number = 1;
    private isOnClick: boolean = false;
    private curLunShu: number = 0;
    private totalLunshu: number = 0;
    private numList = [];
    private rightNum: number = 0;
    private wrongNum: number = 0;
    private superNum: number = 0
    private fluencyNum: number = 0;
    //计时器
    private setOutTimerList = [];
    private totalTimer = 50;
    private curCount = 0;
    //单轮完成时间
    private totalMinTimer = 1;
    private lastTimer = 0;
    private curTimer = 0;
    //连击数
    private combatantNumber = 0;
    //连击获得的金币
    private combatantTotalCount = 0;
    private curChooseWeaponData = null;
    private forgePrefabList = [];
    private curLunShuDataList = [];

    public static sendData(data): Promise<GameWindow> {
        return Context.get().startWindow(GameWindow).then(gameWindow => {
            gameWindow.initData(data);
            return Promise.resolve(gameWindow)
        })
    }
    public onStart() {

    }
    public initData(data) {
        cc.log("data", data)
        this.curChooseWeaponData = data;
        this.onShowUI();
        this.curCount = this.totalTimer;
        var self = this;
        setTimeout(self.showTime.bind(self), 1000)

    }
    public listen(): string[] {
        return []
    }

    public handleMessage(message: string, args: any[]): boolean {
        switch (message) {
        }
        return false
    }
    public onBtnClick(e: cc.Event.EventTouch) {
        if (this.isOnClick == false) return;
        var curForgePre = this.forgePrefabList[this.count - 1];
        this["Btn" + this.numList[this.count - 1]].node.getChildByName("label").getComponent(cc.Label).string = "";
        var curPrefab = null;
        var fluencyAnim = null;
        var curAnim = null;
        var forgeStateSp = curForgePre.getComponent(cc.Sprite);
        var forgeStateUrl = null;
        if (Number(e.currentTarget.name) == this.numList[this.count - 1]) {
            cc.log("正确");
            curAnim = cc.instantiate(this.goldAnimPrefab);
            curPrefab = cc.instantiate(this.combatant);
            this.rightNum += 1;
            this.combatantNumber++;
            this.getCombatantNum();
            curAnim.x = e.currentTarget.x;
            curAnim.y = e.currentTarget.y;
            curPrefab.x = this.actionNode.x - 150;
            curPrefab.y = this.actionNode.y;
            e.currentTarget.addChild(curAnim);
            curAnim.getComponent(cc.Animation).play("goldAnim")
            forgeStateUrl = "image/light_2";
            this.curTimer = cc.sys.now();
            if (this.lastTimer <= 0) {
                this.lastTimer = this.curTimer;
            }
            else {
                if ((this.curTimer - this.lastTimer) / 1000 < 0.5) {
                    //流畅
                    this.fluencyNum++;
                    fluencyAnim = cc.instantiate(this.fluencyAnim);
                    fluencyAnim.x = e.currentTarget.x;
                    fluencyAnim.y = e.currentTarget.y;
                    e.currentTarget.addChild(fluencyAnim);
                    fluencyAnim.getComponent(cc.Animation).play("fluency");
                }
                this.lastTimer = this.curTimer;
            }
            //显示连击数
            if (this.combatantNumber > 1) {
                curPrefab.getChildByName("counLabel").getComponent(cc.Label).string = String(this.combatantNumber);
            }
            else {
                curPrefab.getChildByName("counLabel").getComponent(cc.Label).string = ""
            }
        }
        else {
            cc.log("错误");
            curPrefab = cc.instantiate(this.Lprefab);
            curAnim = cc.instantiate(this.subAnim);
            this.curCount -= 2;
            this.wrongNum += 1;
            this.combatantNumber = 0;
            curAnim.x = e.currentTarget.x;
            curAnim.y = e.currentTarget.y;
            curPrefab.x = this.actionNode.x;
            curPrefab.y = this.actionNode.y;
            curAnim.getComponent(cc.Animation).play("sub");
            e.currentTarget.addChild(curAnim);
            forgeStateUrl = "image/light_3";
        }
        this.getSprite(forgeStateUrl, forgeStateSp);

        var self = this;
        this.actionNode.addChild(curPrefab);
        //this.actionNode.addChild(comAnim);
        var st = setTimeout(function () {
            self.actionNode.removeChild(curPrefab);
            if (curAnim != null) {
                e.currentTarget.removeChild(curAnim);
            }
            if (fluencyAnim != null) {
                e.currentTarget.removeChild(fluencyAnim);
            }
            self.combatantNumberLabel.getComponent(cc.Label).string = "";
        }, 500)
        this.countProgressBar.getComponent(cc.ProgressBar).progress = this.count / this.numList.length;
        this.count++;
        var self = this;
        //当前轮是否点击完成
        if (this.count > this.numList.length) {
            let t = timer.timeEnd("clickTimer") / 1000;
            this.lastTimer = 0;
            this.curTimer = 0;
            if (this.combatantNumber >= (this.count - 1)) {
                cc.log("全部正确")
                this.curCount += 2;
                this.countProgressBar.node.getChildByName("add").active = true;
                if (t < 1) {
                    cc.log("超凡");
                    this.showSuperUI();
                }
            }
            this.count = 1;
            this.numList = [];
            this.isOnClick = false;
            this.isClick(false);
            //所有轮都已完成

            if (this.curLunShu >= this.totalLunshu) {
                this.showWeaponUI.active = true;
                if (this.curChooseWeaponData[0]["id"] != 1001) {
                    SettlementWindow.sendData(this.curChooseWeaponData, this.rightNum, this.wrongNum, this.fluencyNum,
                        this.combatantNumber, this.superNum, this.combatantTotalCount);
                }
                else {
                    Context.get().messenger.sendMessage(WxEvent.ON_FORGINGSUCCESS, [this.rightNum])
                    this.context.startWindow(ForgeWindow);
                    this.context.closeWindow(GameWindow);
                }
                for (let i in this.setOutTimerList) {
                    if (this.setOutTimerList[i]) {
                        clearTimeout(this.setOutTimerList[i]);
                    }
                }
                this.curLunShu = 0;
            }
            else {
                setTimeout(self.onShowUI.bind(self), 500)
            }
            setTimeout(function () {
                self.countProgressBar.node.getChildByName("add").active = false;
                self.countProgressBar.getComponent(cc.ProgressBar).progress = 0;
                for (let i = 0; i < self.forgePrefabList.length; i++) {
                    self.toggleNode.removeChild(self.forgePrefabList[i]);
                }
                self.forgePrefabList = [];
            }, 500)

        }
    }
    /******************************************* */
    private onShowUI() {
        cc.log("onShow", this.curLunShu);
        this.isClick(false);
        //this.showWeaponUI.active = false;
        var self = this;
        var lv = this.curChooseWeaponData[1];
        this.label.string = '第' + (this.curLunShu + 1).toString() + "轮";
        var num = Number(this.curLunShu + 1);
        var knockingData = LoadResData.knockingData;
        var first = 0, second = 0, third = 0;
        var first_lunshu = 0, second_lunshu = 0, third_lunshu = 0;
        for (let i = 0; i < knockingData.length; i++) {
            if (lv == knockingData[i]["lv"]) {
                this.totalLunshu = knockingData[i]["lunshu"];
                first_lunshu = knockingData[i]["first_lunshu"];
                second_lunshu = knockingData[i]["second_lunshu"];
                third_lunshu = knockingData[i]["third_lunshu"];
            }
        }
        first = first_lunshu + 1;
        second = first + second_lunshu;
        if (num == first) {
            this.speed.active = true;
        }
        else if (num == second) {
            this.speed.active = true;
        }
        else {
            this.speed.active = false;
        }
        setTimeout(function () {
            self.onRandomNum(self.curLunShu);
            self.speed.active = false;
        }, 700)
    }
    //随机目标
    private onRandomNum(num: number) {
        this.isOnClick = false;
        this.curLunShu++;
        cc.log("curLunShu", this.curLunShu, this.numList);
        var lv = this.curChooseWeaponData[1];
        var data = this.getCurWeaponLvInfo(lv);
        var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        if (num < data[0][0]) {
            for (let i = 0; i < data[0][1]; i++) {
                let a = Math.floor(Math.random() * list.length + 1);
                this.numList.push(list[a - 1]);
                list.splice(a - 1, 1);
            }
        }
        else if (num >= data[1][0] && num < data[2][0]) {
            for (let i = 0; i < data[1][1]; i++) {
                let a = Math.floor(Math.random() * list.length + 1);
                this.numList.push(list[a - 1]);
                list.splice(a - 1, 1);
            }
        }
        else {
            for (let i = 0; i < data[2][1]; i++) {
                let a = Math.floor(Math.random() * list.length + 1);
                this.numList.push(list[a - 1]);
                list.splice(a - 1, 1);
            }
        }
        var curForgePre = null;
        var sp, url;
        for (let i = 0; i < this.numList.length; i++) {
            if (this.numList.length < 4) {
                this.toggleNode.getComponent(cc.Layout).paddingLeft = 60;
            }
            curForgePre = cc.instantiate(this.forgeState);
            this.forgePrefabList.push(curForgePre);
            this.toggleNode.addChild(curForgePre);
            sp = curForgePre.getComponent(cc.Sprite);
            url = "image/light_1";
            this.getSprite(url, sp);
        }
        this.showButtonMc(0);
    }
    //顺序播放需要点击的目标动画
    private showButtonMc(count: number) {
        cc.log("showButtonMc", this.numList);
        var self = this;
        var num: number = count;
        var sp = this["Btn" + this.numList[num]].node.getChildByName("Background").getComponent(cc.Sprite);
        this.getSprite("image/cub2", sp);
        var t = setTimeout(function () {
            num++;
            if (num >= self.numList.length) {
                self.isOnClick = true;
                self.isClick(true);
            }
            else {
                self.showButtonMc(num);
            }
            self.getSprite("image/cub1_1", sp);
            self.totalMinTimer = cc.sys.now();
            timer.time("clickTimer");
        }, 1000);
        this.setOutTimerList.push(t);
    }
    private isClick(b: boolean) {
        for (let i = 1; i <= 9; i++) {
            this["Btn" + i].getComponent(cc.Button).interactable = b;
        }

    }
    private getSprite(url, sprite) {
        if (url == null) {
            return;
        }
        cc.loader.loadRes(url, cc.SpriteFrame, function (err, spriteFrame) {
            if (!err) {
                sprite.spriteFrame = spriteFrame;
            }
        });
    }
    private showTime(): any {
        var self = this;
        self.timerLabel.string = String(this.curCount.toFixed(2)) + "s";
        this.timerProgressBar.getComponent(cc.ProgressBar).progress = this.curCount / this.totalTimer;
        if (this.curCount > 0) {
            this.curCount--;
            var t = setTimeout(self.showTime.bind(self), 1000);
            this.setOutTimerList.push(t);
        }
        else {
            //清除所有定时器
            for (let i in this.setOutTimerList) {
                if (this.setOutTimerList[i]) {
                    clearTimeout(this.setOutTimerList[i]);
                }
            }
            if (this.curLunShu > this.totalLunshu) {
                //判断是自己武器还是其他武器  1001自己武器ID
                if (this.curChooseWeaponData[0]["id"] != 1001) {
                    SettlementWindow.sendData(this.curChooseWeaponData, this.rightNum, this.wrongNum, this.fluencyNum, this.combatantNumber, this.superNum, this.combatantTotalCount);
                }
                else {
                    Context.get().messenger.sendMessage(WxEvent.ON_FORGINGSUCCESS, [this.rightNum])
                    this.context.startWindow(ForgeWindow);
                }
            }
            else {
                this.context.startWindow(LoseWindow);
            }

        }
    }
    //超凡表现
    private showSuperUI() {
        this.superNum++;
        var curPrefab;
        curPrefab = cc.instantiate(this.Superprefab);
        curPrefab.x = this.superNode.x;
        curPrefab.y = this.superNode.y;
        this.superNode.addChild(curPrefab);
        var self = this;
        setTimeout(() => {
            self.superNode.removeChild(curPrefab);
        }, 500);
    }
    //获取当前武器每轮需要锻造次数
    private getCurWeaponLvInfo(lv: number) {
        var knockingData = LoadResData.knockingData;
        var first = 0, second = 0, third = 0;
        var first_lunshu = 0, second_lunshu = 0, third_lunshu = 0;
        var list = [];
        for (let i = 0; i < knockingData.length; i++) {
            if (lv == knockingData[i]["lv"]) {
                this.totalLunshu = knockingData[i]["lunshu"];

                first_lunshu = knockingData[i]["first_lunshu"];
                second_lunshu = knockingData[i]["second_lunshu"];
                third_lunshu = knockingData[i]["third_lunshu"];

                first = knockingData[i]["first"];
                second = knockingData[i]["second"];
                third = knockingData[i]["third"];
                list.push([first_lunshu, first]);
                list.push([second_lunshu, second]);
                list.push([third_lunshu, third]);
                return list;
            }
        }
    }
    //计算连击获得的金币
    private getCombatantNum() {
        var weapons = LoadResData.weaponsData;
        var curWeaponLv: any = LocalStorage.getObj("weaponLv");
        for (let i in curWeaponLv) {
            for (let j in weapons) {
                if (curWeaponLv[i]["id"] == weapons[j]['skill_type']) {
                    switch (weapons[j]['skill_type']) {
                        case 1: {
                            this.combatantTotalCount += Number(curWeaponLv[i]['lv']) * Number(weapons[j]['skill_base']);
                            break;
                        }
                    }
                }
            }
        }
    }
}